package com.googlecode.jmicroerp.wicket.index;

import com.googlecode.jmicroerp.wicket.DefaultViewPage;
import com.googlecode.jmicroerp.model.Magazin;
import com.googlecode.jmicroerp.model.Stoc;
import com.googlecode.jmicroerp.repository.GenericProperty;
import com.googlecode.jmicroerp.repository.GenericRestriction;
import com.googlecode.jmicroerp.repository.GenericOrder;
import com.googlecode.jmicroerp.service.BonService;
import com.googlecode.jmicroerp.service.GenericService;
import com.googlecode.jmicroerp.wicket.vanzare.PosPage;
import com.googlecode.jmicroerp.wicket.butoaie.IndexAddPage;
import com.googlecode.jmicroerp.wicket.magazin.WizardPage;
import com.googlecode.jmicroerp.wicket.stocuri.EditareStocPage;
import com.googlecode.jmicroerp.wicket.stocuri.VizualizareStocPage;
import com.googlecode.jmicroerp.wicket.stocuri.IstoricPage;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import org.apache.wicket.ajax.AbstractAjaxTimerBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.time.Duration;
import com.googlecode.jmicroerp.wicket.SecuredWebSession;
import java.util.ArrayList;

/**
 *
 * @author alex
 */
public class IndexPage extends DefaultViewPage {

    @SpringBean(name = "bonService")
    private BonService bonService;
    @SpringBean(name = "genericService")
    private GenericService<Stoc> stocService;
    @SpringBean(name = "genericService")
    private GenericService<Magazin> magazinService;

    private Link createNavigationLink(String id, final Class<? extends WebPage> pageClass) {
        Link link = new Link(id) {
            @Override
            public void onClick() {
                setResponsePage(pageClass);
            }
        };
        return link;
    }

    private class BonView extends ListView<Object[]> {

        public BonView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            li.add(new Label("magazin", object[0].toString()));
            li.add(new Label("bonuri", object[1].toString()));
            li.add(new Label("suma", object[2].toString()));
        }
    }

    private class StoreView extends ListView<Magazin> {

        public StoreView(String id, List<Magazin> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Magazin> li) {
            Magazin magazin = li.getModelObject();
            li.add(new Label("store", magazin.getDenumire()).add(new AttributeAppender("href", "#" + magazin.getDenumire())));
            if (magazin.getDenumire().equals(((SecuredWebSession) getSession()).getMagazin().getDenumire())) {
                li.add(new AttributeAppender("class", "active"));
            }
                                   
        }
    }

    private class StoreStocView extends ListView<Magazin> {

        public StoreStocView(String id, List<Magazin> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Magazin> li) {
            final Magazin magazin = li.getModelObject();
            li.add(new AttributeAppender("id", magazin.getDenumire()));
            if (magazin.getDenumire().equals(((SecuredWebSession) getSession()).getMagazin().getDenumire())) {
                li.add(new AttributeAppender("class", " active"));
            }
            
            GenericRestriction resMag = new GenericRestriction(new GenericProperty("recipient").setReference(new GenericProperty("magazin").setReference(new GenericProperty("id"))), magazin.getId());
            GenericRestriction resAct = new GenericRestriction(new GenericProperty("recipient").setReference(new GenericProperty("activ")), Boolean.TRUE);
            
            GenericOrder ordMag = new GenericOrder(new GenericProperty("recipient").setReference(new GenericProperty("ordine")), true);
            
            List<Stoc> stocuri = stocService.getList(Stoc.class, Arrays.asList(resMag,resAct), Arrays.asList(ordMag));
            li.add(new Label("lblSize", stocuri.size()));
            
            StocView recipiente = new StocView("recipient", stocuri);
            li.add(recipiente);
            
            Link linkWizard = new Link("linkWizard") {
                @Override
                public void onClick() {
                	setResponsePage(new WizardPage((Long) magazin.getId()));
                }
            };
            li.add(linkWizard);
        
        }
    }

    public class StocView extends ListView<Stoc> {

        public StocView(String id, List<Stoc> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Stoc> li) {
            final Stoc stoc = li.getModelObject();
            BigDecimal nivel = stoc.getCantitate().divide(stoc.getRecipient().getTipRecipient().getCapacitateAlerta(), 2, RoundingMode.UP);
            nivel = nivel.multiply(new BigDecimal("100"));
            
            WebMarkupContainer wmc = new WebMarkupContainer("stoc_recipient");
            wmc.add(new AttributeAppender("class", " " + stoc.getRecipient().getTipRecipient().getCategorie().getCodCuloare()));
            
            li.add(new Label("denumire", stoc.getRecipient().getDenumire()));
            li.add(new Label("stoc", stoc.getCantitate()));
            wmc.add(new Label("nivel", "").add(new AttributeAppender("style", "width: " + nivel + "%;")));
            li.add(wmc);
            Link detailLink = new Link("detailLink") {
                @Override
                public void onClick() {
                    setResponsePage(new IstoricPage((Long) stoc.getRecipient().getId()));
                }
            };
            li.add(detailLink);
            Link editLink = new Link("editLink") {
                @Override
                public void onClick() {
                    setResponsePage(new EditareStocPage((Long) stoc.getId()));
                }
            };
            li.add(editLink);
            
            
        }
    }
    
    private String createBonuriByMagazin7Days() {
        // String options = "lines: {show: true}, points: {show: true}, ";
        
        //String funct = "function GetDay(i) {\n var d = new Date();\n var weekday = new Array(7); \n weekday[0] = \"Du\"; weekday[1] = \"Lu\"; weekday[2] = \"Ma\";    weekday[3] = \"Mi\"; weekday[4] = \"Jo\"; weekday[5] = \"Vi\"; weekday[6] = \"Sa\";\n var n = weekday[d.getDay()-i]; \n return n; }\n";
        
        String funct = "function GetDay(i) {\n var d = new Date();\n d.setHours(0,0,0,0);\n var n = (new Date(((d.setDate(d.getDate()+i))))).getTime();; \n return n; }\n";
        
        String options = "{lines: {show: true}, points: {show: true}, grid: {hoverable: true}, xaxis: {mode: \"time\", minTickSize: [1, \"day\"], timeformat: \"%a\", dayNames: [\"DU\",\"LU\",\"MA\",\"MI\",\"JO\",\"VI\",\"SA\"]}}";
        
        String divadd = "$(\"<div id='tooltip'></div>\").css({position: \"absolute\",display: \"none\",border: \"1px solid #fdd\",padding: \"2px\",\"background-color\": \"#fee\",opacity: 0.80	}).appendTo(\"body\");\n";
        
        String result = funct;
        result += "\n$(function() {\n";
        
        List<Magazin> magazine = magazinService.getList(Magazin.class, new ArrayList<GenericRestriction>(), new ArrayList<GenericOrder>());
        int order = 1;
        
        for (Magazin magazin : magazine) {
            result += "    var d" + order + "=[";
            List<BigDecimal> vanzari = bonService.queryVanzariLast7DaysByMagazin(magazin.getId());
            for (int i = 0; i < vanzari.size(); i++) {
                result += "[GetDay(" + (i-6) + ")," + vanzari.get(i).toString() + "]";
                if (i < vanzari.size() - 1) {
                    result += ",";
                }
            }
            result += "];\n";
            order++;
        }
        
        result += "$.plot(\"#placeholder\", [";
        
        order = 1;
        for (Magazin magazin : magazine) {
            result += "{ label: \"" + magazin.getDenumire() + "\", data: d" + order + " }";
            if (order != magazine.size()) {
                result += ",";
            }
            order++;
        }
        result += "],"+ options +");\n";
        result += divadd;
        
        String hooveradd = "$(\"#placeholder\").bind(\"plothover\", function (event, pos, item) {\n";
        hooveradd += "if (item) {\n";
        hooveradd += "var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2);\n";
        hooveradd += " $(\"#tooltip\").html(item.series.label + \" = \" + y).css({top: item.pageY+5, left: item.pageX+5}).fadeIn(200);}\n";
        hooveradd += " else {$(\"#tooltip\").hide();}\n";
        hooveradd += "});\n";
        
        result += hooveradd;
        //end
        result += "\n})";
        return result;
    }
  
    public IndexPage() {
        Link linkPos = createNavigationLink("vanzare", PosPage.class);
        add(linkPos);
        final Label lblVandAzi = new Label("vanzariAzi", bonService.queryVanzariAzi() == null ? "0.00" : bonService.queryVanzariAzi().toString());
        linkPos.add(lblVandAzi);

        final BonView bonAziView = new BonView("bonuriAzi", bonService.queryBonuriByMagazinToday());
        final BonView bon7ziView = new BonView("bonuri7zile", bonService.queryBonuriByMagazin7Day());
        final BonView bonLunView = new BonView("bonuriLuna", bonService.queryBonuriByMagazinMonth());
        Object[] bonDataAzi = bonService.queryBonuriToday();
        Object[] bonData7Zile = bonService.queryBonuri7Day();
        Object[] bonData30Zile = bonService.queryBonuriMonth();
        final Label lblTotAzi = new Label("totalBonuriAzi", bonDataAzi[0] == null ? "---" : bonDataAzi[0].toString());
        final Label lblSumAzi = new Label("totalSumaAzi", bonDataAzi[1] == null ? "---" : bonDataAzi[1].toString());
        final Label lblTot7Zi = new Label("totalBonuri7zile", bonData7Zile[0] == null ? "---" : bonData7Zile[0].toString());
        final Label lblSum7Zi = new Label("totalSuma7zile", bonData7Zile[1] == null ? "---" : bonData7Zile[1].toString());
        final Label lblTot30Z = new Label("totalBonuri30Zile", bonData30Zile[0] == null ? "---" : bonData30Zile[0].toString());
        final Label lblSum30Z = new Label("totalSuma30Zile", bonData30Zile[1] == null ? "---" : bonData30Zile[1].toString());
        add(lblTotAzi);
        add(lblSumAzi);
        add(lblTot7Zi);
        add(lblSum7Zi);
        add(lblTot30Z);
        add(lblSum30Z);

        add(bonAziView);
        add(bon7ziView);
        add(bonLunView);
        
        Link linkStoc = createNavigationLink("lnkStoc", VizualizareStocPage.class);
        add(linkStoc);
      
        // List<Magazin> magazine = magazinService.getList(Magazin.class, null, null);
        GenericOrder ord = new GenericOrder(new GenericProperty("denumire"));
        List<Magazin> magazine = magazinService.getList(Magazin.class, null, Arrays.asList(ord));
        final StoreView stores = new StoreView("storeView", magazine);
        final StoreStocView storeStocs = new StoreStocView("stocuri", magazine);
        add(stores);
        add(storeStocs);
        add(new AbstractAjaxTimerBehavior(Duration.seconds(20)) {
            @Override
            protected void onTimer(AjaxRequestTarget art) {
                bonAziView.setList(bonService.queryBonuriByMagazinToday());
                bonAziView.modelChanged();

                bon7ziView.setList(bonService.queryBonuriByMagazin7Day());
                bon7ziView.modelChanged();

                bonLunView.setList(bonService.queryBonuriByMagazinMonth());
                bonLunView.modelChanged();

                Object[] bonDataAzi = bonService.queryBonuriToday();
                Object[] bonData7Zile = bonService.queryBonuri7Day();
                Object[] bonData30Zile = bonService.queryBonuriMonth();

                lblVandAzi.setDefaultModelObject(bonService.queryVanzariAzi() == null ? "0.00" : bonService.queryVanzariAzi().toString());
                lblVandAzi.modelChanged();
                lblTotAzi.setDefaultModelObject(bonDataAzi[0] == null ? "---" : bonDataAzi[0].toString());
                lblTotAzi.modelChanged();
                lblSumAzi.setDefaultModelObject(bonDataAzi[1] == null ? "---" : bonDataAzi[1].toString());
                lblSumAzi.modelChanged();
                lblTot7Zi.setDefaultModelObject(bonData7Zile[0] == null ? "---" : bonData7Zile[0].toString());
                lblTot7Zi.modelChanged();
                lblSum7Zi.setDefaultModelObject(bonData7Zile[1] == null ? "---" : bonData7Zile[1].toString());
                lblSum7Zi.modelChanged();
                lblTot30Z.setDefaultModelObject(bonData30Zile[0] == null ? "---" : bonData30Zile[0].toString());
                lblTot30Z.modelChanged();
                lblSum30Z.setDefaultModelObject(bonData30Zile[1] == null ? "---" : bonData30Zile[1].toString());
                lblSum30Z.modelChanged();

                storeStocs.modelChanged();

                art.add(IndexPage.this);
            }
        });
        
        Label plot = new Label("plotValues", createBonuriByMagazin7Days());
        plot.setEscapeModelStrings(false);
        add(plot);
    }
}
